package com.ssm.modular.login.servlet;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import com.ssm.modular.login.dao.SysUserDao;
import com.ssm.modular.login.dto.SysLoginLog;
import com.ssm.modular.sysUser.dto.SysUser;
import com.ssm.util.LocalhostIp;
import com.ssm.util.TimeStamp;
import com.ssm.util.UUid;

/**
* @ClassName: LoginServlet
* @Description: TODO 登录验证
* @author ym
* @date 2017年12月19日 下午3:41:41
*/ 
@WebServlet("/LoginServlet")
public class LoginServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
	private static final String LOGINSUCCESS = "登录成功";
	private static final String LOGINFAILURE = "登录失败";
	    
    public LoginServlet() {
        super();
    }

	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
			 response.setContentType("text/html;charset=utf-8");
	        //获取用户名和密码
	        String username = request.getParameter("username");
	        String password = request.getParameter("password");
	        //获取UserDao实例
	        SysUserDao SysUserDao = new SysUserDao();
	        SysUser user = SysUserDao.find(username, password);
	        // 判断user是否为空
	        if(user != null){
	             HttpSession session = request.getSession();  
	             session.setAttribute("sname", username);//登陆的用户名  
	             String sid=session.getId();//SessionId  
	             session.setAttribute("sid", sid);  
	        	SysUserDao.insertLoginLog(user ,LOGINSUCCESS);//登录日志
	        	response.sendRedirect("source/jsp/index.jsp");
	        }else{
	        	SysUser sysUser = new SysUser();
	        	sysUser.setLoginName(username);
	        	SysUserDao.insertLoginLog(sysUser ,LOGINFAILURE);//登录日志
	        	request.setAttribute("message", "用户名或密码错误！");
	        	request.getRequestDispatcher("/login.jsp").forward(request, response);
	           }
	        }

	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		   doGet(request, response);
		   }

	
}
